import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_learn_vi/src/bean/bean_global.dart';
import 'package:flutter_learn_vi/src/common/global.dart';
import 'package:flutter_learn_vi/src/common/user_helper.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/app_upgrade.dart';
import 'package:flutter_learn_vi/src/page/common/common_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/user_protocol_page.dart';
import 'package:flutter_learn_vi/src/page/mine/password/update_password_page.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';
import 'package:get/get.dart';
import 'package:mobpush_plugin/mobpush_plugin.dart';
import 'package:notification_permissions/notification_permissions.dart';
import 'package:package_info/package_info.dart';

import '../login/kuangdeng/kuang_deng_login2_page.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/12/3.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///设置中心
///lib/src/page/mine/settings_page.dart
class SettingsPage extends StatefulWidget {
  final int pageIndex;

  const SettingsPage({Key key, this.pageIndex = 0}) : super(key: key);

  @override
  _SettingsPageState createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage>
    with WidgetsBindingObserver {
  String _version = "";

  bool _pushFunction = false;
  String _registrationId = "";
  List<dynamic> _pushTagList = [];
  String _pushAlias = "";

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    initFunction();
  }

  void initFunction() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String appName = packageInfo.appName;
    String packageName = packageInfo.packageName;
    String version = packageInfo.version;
    String buildNumber = packageInfo.buildNumber;
    _version = version;
    LogUtils.e("获取到版本号 $_version");

    _pushFunction = await checkPush();
    if (mounted) {
      setState(() {});
    }
  }

  Future<bool> checkPush({bool background: false}) async {
    PermissionStatus status =
        await NotificationPermissions.getNotificationPermissionStatus();
    switch (status) {
      case PermissionStatus.denied:
        break;
      case PermissionStatus.granted:
        LogUtils.e("有推送通知权限");

        try {
          MobpushPlugin.getRegistrationId().then((Map<String, dynamic> ridMap) {
            _registrationId = ridMap['res'].toString();
            print('------>#### registrationId: ' + _registrationId);
            if (mounted) {
              setState(() {});
            }
          });
          MobpushPlugin.getTags().then((Map<String, dynamic> tagsMap) {
            if (tagsMap['res'] == null) {
              _pushTagList = [];
            } else {
              _pushTagList = tagsMap['res'].toList();
            }
            String error = tagsMap['error'];

            print(
                ">>>>>>>>>>>>>>>>>>>>>>>>>>> getTags -> res: $_pushTagList error: $error");
          });
          MobpushPlugin.getAlias().then((Map<String, dynamic> aliasMap) {
            String res = aliasMap['res'];
            String error = aliasMap['error'];
            _pushAlias = res;
            print(
                ">>>>>>>>>>>>>>>>>>>>>>>>>>> getAlias -> res: $res error: $error");
          });
        } on PlatformException {
          _registrationId = '推送暂时无法获取';
        }
        return true;
        break;
      case PermissionStatus.unknown:
        break;
      case PermissionStatus.provisional:
        break;
      default:
        return null;
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: Text(widget.pageIndex == 0 ? "设置中心" : "设置"),
        ),
        body: Column(
          children: [
            Expanded(
              child: ListView(
                children: [
                  //第一部分显示用户协议相关
                  ListTile(
                    leading:
                        Icon(widget.pageIndex == 0 ? Icons.person : Icons.paste),
                    title: Text("用户协议"),
                    trailing: Icon(Icons.arrow_forward_ios, size: 15),
                    onTap: () {
                      //用户协议 弹框显示
                      showUserProtocolPage(
                        context: context,
                        isOneButton: true,
                      );
                    },
                  ),
                  ListTile(
                    leading: Icon(Icons.update),
                    title: Text("修改密码"),
                    trailing: Icon(Icons.arrow_forward_ios, size: 15),
                    onTap: () {
                      NavigatorUtils.pushPage(context, UpdatePasswordPage());
                    },
                  ),
                  ListTile(
                    leading: Icon(Icons.phonelink_erase),
                    title: Text("注销账户"),
                    trailing: Icon(Icons.arrow_forward_ios, size: 15),
                    onTap: () {
                      unRegisterFunction();
                    },
                  ),
                  //第二部分检查更新功能

                  ListTile(
                    leading: Icon(widget.pageIndex == 0
                        ? Icons.web_sharp
                        : Icons.settings_backup_restore_outlined),
                    title: Text(Platform.isAndroid
                        ? "检查更新 当前版本 $_version"
                        : "当前版本 $_version"),
                    trailing: Icon(Icons.arrow_forward_ios, size: 15),
                    onTap: () {
                      if (Platform.isAndroid) {
                        check();
                      } else {
                        // InstallPluginCustom.gotoAppStore(
                        //     "https://apps.apple.com/cn/app/id1445633375");
                      }
                    },
                  ),
                  ListTile(
                    leading: Icon(
                      Icons.published_with_changes,
                      color: _pushFunction ? Colors.green : Colors.red,
                    ),
                    title: Text(_pushFunction ? "推送 $_registrationId" : "通知无权限"),
                    trailing: Icon(Icons.arrow_forward_ios, size: 15),
                    onTap: () {
                      LogUtils.e("点击了推送");
                      if (!_pushFunction) {
                        NotificationPermissions.requestNotificationPermissions(
                            iosSettings: const NotificationSettingsIos(
                                sound: true, badge: true, alert: true));
                      } else {
                        showDialog(
                            context: context,
                            builder: (context) {
                              return AlertDialog(
                                title: Text("推送通知"),
                                content: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    GestureDetector(
                                        onTap: () {},
                                        child: Text(
                                          "识别码   $_registrationId",
                                          style: TextStyle(color: Colors.blue),
                                        )),
                                    SizedBox(
                                      height: 12,
                                    ),
                                    Text("识别标签 $_pushTagList"),
                                    SizedBox(
                                      height: 12,
                                    ),
                                    Text("识别别名 $_pushAlias"),
                                  ],
                                ),
                                actions: <Widget>[
                                  TextButton(
                                      onPressed: () {
                                        Navigator.pop(context);
                                      },
                                      child: Text("知道了"))
                                ],
                              );
                            });
                      }
                    },
                  ),
                  //第三部分检查登录
                  buildLoginRow(context),
                ],
              ),
            ),
            Container(
              padding: EdgeInsets.only(bottom: 22),
              child: Text(
                'APP备案号:京ICP备18060046号-5A',
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 12, color: Colors.grey),
              ),
            ),
          ],
        ));
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      initFunction();
    }
  }

  Widget buildLoginRow(BuildContext context) {
    String text = "退出登录";
    if (!UserHelper.getInstance.userIsLogin) {
      text = "去登录";
    }

    if (widget.pageIndex == 1) {
      return Container(
        margin: EdgeInsets.only(top: 60),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 200,
              child: ElevatedButton(
                child: Text("$text"),
                onPressed: () {
                  exitFunction();
                },
              ),
            )
          ],
        ),
      );
    }
    return ListTile(
      leading: Hero(
        tag: "loginTag",
        child: Material(
          child: Icon(Icons.exit_to_app),
          color: Colors.transparent,
        ),
      ),
      title: Text("$text"),
      trailing: Icon(Icons.arrow_forward_ios, size: 15),
      onTap: () {
        exitFunction();
      },
    );
  }

  void check() async {
    //获取当前App的版本信息
    PackageInfo packageInfo = await PackageInfo.fromPlatform();

    String appName = packageInfo.appName;
    String packageName = packageInfo.packageName;
    String version = packageInfo.version;
    String buildNumber = packageInfo.buildNumber;

    LogUtils.e("appName $appName");
    LogUtils.e("packageName $packageName");
    LogUtils.e("version $version");
    LogUtils.e("buildNumber $buildNumber");

    checkAppVersion(context, showToast: true, page: "setting");
  }

  //注销账号
  void unRegisterFunction() {
    showCommonAlertDialog(
        context: context,
        cancleText: "取消",
        contentMessag: "注销账户功能，将删除你此账号下的所有内容，并不可恢复，是否要继续？？？",
        selectText: "确认",
        selectCallBack: () {
          unRegisterNetWorkFunction();
        });
  }

  void unRegisterNetWorkFunction() async {
    ResponseInfo partResponseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.UN_REGISTER_URL,
    );
    if (partResponseInfo.success) {
      ToastUtils.showToast("已注销");
      UserHelper.getInstance.removeUserBean();
      rootStreamController.add(GlobalBean(202, "关闭"));
      NavigatorUtils.pop(context);
    } else {
      ToastUtils.showToast("注销失败请重试");
    }
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  void exitFunction() {
    //关闭首页面
    // rootStreamController.add(GlobalBean(202, "关闭"));
    // NavigatorUtils.pop(context);
    //清除缓存用户信息
    UserHelper.getInstance.exitLogin();
    //关闭首页面
    // rootStreamController.add(GlobalBean(202, "关闭"));
    // NavigatorUtils.pop(context);
    Get.offAll(() => KuangDengLogin2Page());
  }
}
